#include "head.h"

int msqid;

void sigint(int signo) {
	if (msgctl(msqid, IPC_RMID, NULL) == -1) {
		perror("msgctl sigint server");
		exit(1);
	} else {
		printf("Odlaczanie klienta\n");
		return;
	}
}

void readqueue() {
	struct message msg;
	while (msgctl(msqid, IPC_STAT, NULL) != -1) {
		if (msgrcv(msqid,&msg,sizeof(struct message),3,0) == -1){
			perror("msgrcv");
		} else {
			printf("%s",msg.message);
		}
	}
}

int main(int argc, char ** argv) {
	if (argc != 4) {
		printf("Niepoprawne wywolanie. Wywolanie: ./client.o <path> <path> <name>\n");
		return -1;
	}
	key_t srv_key, key;
	int id = 64;
	if ((srv_key = ftok(argv[1], id)) == -1) {
		perror("ftok client srv_key");
		return -2;
	}
	id = 128;
	if ((key = ftok(argv[2], id)) == -1) {
		perror("ftok client key");
		return -4;
	}
	if (signal(SIGINT, sigint) == SIG_ERR ) {
		perror("signal client");
		return -3;
	}
	if ((msqid = msgget(key, IPC_CREAT | 0666)) == -1) {
		perror("msgget client");
		return -5;
	}
	int msqid_srv;
	if ((msqid_srv = msgget(srv_key, 0666)) == -1) {
		perror("msgget client srvkey");
		return -7;
	}
	struct message cl_mess;
	cl_mess.type = 1;
	sprintf(cl_mess.message, "%d", msqid);
	strcpy(cl_mess.login,argv[3]);
	if (msgsnd(msqid_srv, &cl_mess, sizeof(struct message), 0) == -1) {
		perror("msgsend");
		return -8;
	}
	pid_t pid;
	if ((pid = fork()) < 0) {
		perror("fork");
		return -11;
	} else if ( pid == 0) {
		readqueue();
	} else {
		while (1) {
			char * buffer = (char *)malloc(sizeof(char)*512);
			fgets(buffer, sizeof(char)*512, stdin);
			time_t times = time(NULL);
			struct tm * h_time = localtime(&times);
			sprintf(cl_mess.message, "%d:%d:%d %s:%s", h_time->tm_hour, h_time->tm_min, h_time->tm_sec, argv[3], buffer);
			cl_mess.message[strlen(cl_mess.message)+1] = '\0';
			cl_mess.type = 2;
			if (msgsnd(msqid, &cl_mess, sizeof(struct message), 0) == -1) {
				perror("msgsnd");
				return -9;
			}
			sleep(1);
			free(buffer);
		}
	}
	return 0;
}
